﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slam;
using Microsoft.SharePoint;
using Slam.Configuration;
using Slam.Logging;
using Slam.Data;
using Slam.SharePoint;
using Slam.Events;
using System.Xml.Linq;
using SlamCms.SharePoint.Tagging;
using SlamCms.SharePoint.SlamProfiles.ContentItem.Data;
using SlamCms.SharePoint.SlamProfiles.ContentItem.Services;
using System.Threading;

namespace SlamCms.SharePoint.SlamProfiles.ContentItem
{
	public class ContentItemContentTypeItemDeleter : ContentTypeItemDeleter
	{
		private IConfigurationManager _configuration;
		private DataService _dataService;
		private IDataServices _dataServices;
		private string _dataSchema;
		private ILogger _logger;

		#region Constructors

		public ContentItemContentTypeItemDeleter(IDataServices dataServices, IConfigurationManager configuration, ILogger logger)
			: base(dataServices, configuration, logger)
		{
			_configuration = configuration;
			_dataServices = dataServices;
			_dataSchema = ((XmlSqlDataMapping)configuration.DataMapping).GetDataSchema();
			_dataService = new DataService(configuration.GetSection<ConnectionStringSection>("ConnectionStrings").Default);
			_logger = logger;

			_configuration.RegisterSection("ContentItem",
				config =>
				{
					object section = null;
					if (config is XDocument)
					{
						section = new ContentItemProfileSection((XDocument)config);
					}
					return section;
				});
		}

		#endregion

		public override bool Delete(SPListItem listItem)
		{
			EventUtility eventUtility = new EventUtility();
			eventUtility.DisableEventHandlers();

			bool deleteItem = false;

			SPList list = listItem.ParentList;

			if (list.EnableModeration && list.EnableVersioning)
			{
				listItem.SetPublishingStatus();
				if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
				{
					Thread.Sleep(500);
				}
				string status = listItem.GetPublishingStatus();
				if (listItem.HasPublishedVersion && status != ContentItemStatus.Live.Name)
				{
					status = ContentItemStatus.Modified.Name;
				}

				string siteCollection = listItem.Web.Site.ServerRelativeUrl.TrimStart('/');

				ContentItemProfileSection contentItemSection = _configuration.GetSection<ContentItemProfileSection>("ContentItem");
				ContentItemConfiguredType contentItemType = contentItemSection.GetContentItemConfiguredType(siteCollection, "", SlamItemContext.TypeName);

				if (status == ContentItemStatus.Live.Name)
				{
					listItem.Web.AllowUnsafeUpdates = true;
					listItem.ModerationInformation.Status = SPModerationStatusType.Denied;
					listItem.UpdateOverwriteVersion();

					listItem.SetPublishingStatus();

					ContentItemEvents.Update(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Update CT", true);
					//ContentItemEvents.Delete(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Delete CT");
				}
				else if (status == ContentItemStatus.Modified.Name || status == ContentItemStatus.PendingApprovalModified.Name)
				{
					SPFieldUserValue modifiedByUser = new SPFieldUserValue(listItem.Web, listItem[SPBuiltInFieldId.Editor].ToString());
					ContentItemEvents.Delete(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Delete CT");

					listItem.Web.AllowUnsafeUpdates = true;
					listItem.Versions.RestoreByID(listItem.GetLiveVersionId());

					listItem.Web.AllowUnsafeUpdates = true;
					listItem.ModerationInformation.Status = SPModerationStatusType.Approved;
					listItem.UpdateOverwriteVersion();

					listItem.Web.AllowUnsafeUpdates = true;
					listItem[SPBuiltInFieldId.Editor] = modifiedByUser;
					listItem.SystemUpdate(false);

					ContentItemEvents.Update(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Update CT", true);
				}
				else if (status != ContentItemStatus.Retired.Name || !contentItemType.PreventDelete)
				{
					deleteItem = ContentItemEvents.Delete(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Delete CT");
				}
			}
			else
			{
				deleteItem = ContentItemEvents.Delete(listItem, _dataServices, _configuration, _logger, _dataService, _dataSchema, "Delete CT");
			}

			eventUtility.EnableEventHandlers();
			return deleteItem;
		}
	}
}
